<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use library\Controller;
use library\service\AdminService;
use library\service\MenuService;
use library\tools\Data;
use think\Console;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 系统公共操作
 * Class Index
 * @package app\admin\controller
 */
class Index extends Controller
{

    /**
     * 显示后台首页
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $this->title = '系统管理后台';
        $auth = AdminService::instance()->apply(true);
        if(!$auth->isLogin()) $this->redirect('@admin/login');
        $this->menus = MenuService::instance()->getTree();
        if (empty($this->menus) && !$auth->isLogin()) {
            $this->redirect('@admin/login');
        } else {
            $this->fetch();
        }
    }

    /**
     * Describe:查询充值提现记录
     * DateTime: 2020/5/15 0:54
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check(){
        $auth = AdminService::instance()->apply(true);
        if($auth->isLogin()){
            $user = $this->app->session->get('user');
            $authorize = $user['authorize'];
            if(!empty($authorize)){
                $auth_node = Db::name("system_auth_node")->where("auth=$authorize AND (node = 'admin/recharge_record/agree' OR node = 'admin/withdraw_record/agree')")->count();
            }
            if($user['id']==10000||$auth_node>0){
                $withdraw_count = Db::name("LcUserWithdrawRecord")->where(['status'=>0,'warn'=>1])->count();
                // $recharge_count = Db::name("LcUserRechargeRecord")->where(['status'=>0,'warn'=>1])->count();
                // if($withdraw_count>0&&$recharge_count>0){
                //     $this->success("<a style='color:#FFFFFF' data-open='/admin/recharge_record/index.html'>您有{$withdraw_count}条新的提现记录和{$recharge_count}条新的充值记录，请查看！</a>",['url'=>'/static/mp3/cztx.mp3']);
                // }
                if($withdraw_count>0){
                    $this->success("<a style='color:#FFFFFF' data-open='/admin/withdraw_record/index.html'>您有{$withdraw_count}条新的提现记录，请查看！</a>",['url'=>'/static/mp3/tx.mp3']);
                }
                // if ($withdraw_count == 0 && 0 < $recharge_count){
                //     $this->success("<a style='color:#FFFFFF' data-open='/admin/recharge_record/index.html'>您有{$recharge_count}条新的充值记录，请查看！</a>",['url'=>'/static/mp3/cz.mp3']);
                // }
                $this->error("暂无记录");
            }
        }else{
            $this->error("请先登录");
        }
        
    }

    /**
     * Describe:忽略提醒
     * DateTime: 2020/5/15 0:56
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function system_ignore(){
        $auth = AdminService::instance()->apply(true);
        if($auth->isLogin()){
            Db::name("LcUserWithdrawRecord")->where(['warn'=>1])->update(['warn'=>0]);
            Db::name("LcUserRechargeRecord")->where(['warn'=>1])->update(['warn'=>0]);
            $this->success("操作成功");
        }
        $this->error("请先登录");
    }

    /**
     * 系统报表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function main()
    {
        /*$this->think_ver = \think\App::VERSION;
        $this->mysql_ver = Db::query('select version() as ver')[0]['ver'];*/
        $auth = AdminService::instance()->apply(true);
        if($auth->isLogin()){
            $now = date('Y-m-d H:i:s');//现在
            $today = date('Y-m-d 00:00:00');//今天0点
            $yesterday = date('Y-m-d 00:00:00', strtotime($now)-86400);//昨天0点
            $i_time = $this->request->param('i_time');
            
            //用户数量
            $this->user_count = Db::name('LcUser')->count();
            //用户余额
            $this->user_money_sum = Db::name('LcUser')->sum('money');
            //今日注册
            $this->user_count_today = Db::name('LcUser')->where("time BETWEEN '$today' AND '$now'")->count();
            //今日登录
            $this->user_login_count_today = Db::name('LcUser')->where("logintime BETWEEN '$today' AND '$now'")->count();
            //充值笔数
            $this->recharge_count = Db::name('LcUserRechargeRecord')->where("status = 1")->count();
            //充值金额
            $this->recharge_sum = Db::name('LcUserRechargeRecord')->where("status = 1")->sum('money');
            //提现笔数
            $this->withdraw_count = Db::name('LcUserWithdrawRecord')->where("status = 1")->count();
            //提现金额
            $this->withdraw_sum = Db::name('LcUserWithdrawRecord')->where("status = 1")->sum('money');
            //投资笔数
            $this->invest_count = Db::name('LcInvest')->count();
            //投资人数
            $this->invest_user_count = Db::name('LcInvest')->group('uid')->count();
            //投资金额
            $this->invest_sum = Db::name('LcInvest')->sum('money');
            //投资收益
            $this->invest_reward = Db::name('LcUserFunding')->where("type = 1 AND fund_type = 6")->sum('money');
            //系统操作（增加）
            $funding_sys_1_sum = Db::name('LcUserFunding')->where("type = 1 AND fund_type = 1")->sum('money');
            //系统操作（减少）
            $funding_sys_2_sum = Db::name('LcUserFunding')->where("type = 2 AND fund_type = 1")->sum('money');
            //系统操作
            $this->funding_sys_sum = $funding_sys_1_sum - $funding_sys_2_sum;
            //系统奖励
            $this->sys_reward = Db::name('LcUserFunding')->where("type = 1 AND fund_type IN (7,8,9,10,11,12,13,14)")->sum('money');
            
            
            $table = $this->finance_report($now,$today,$yesterday,$i_time);
            $this->today = $table['today'];
            $this->yesterday = $table['yesterday'];
            $this->month = $table['month'];
            $this->last_month = $table['last_month'];
            $this->day = $table['day'];
            
            $this->fetch();
        }
        $this->error("请先登录");
    }

    private function finance_report($now,$today,$yesterday,$i_time){
        //综合报表
        //今日
        $today1['recharge'] = Db::name('LcUserRechargeRecord')->where("time BETWEEN '$today' AND '$now' AND status = 1")->sum('money');
        $today1['recharge_count'] = Db::name('LcUserRechargeRecord')->where("time BETWEEN '$today' AND '$now' AND status = 1")->count();
        $today1['withdraw'] = Db::name('LcUserWithdrawRecord')->where("time BETWEEN '$today' AND '$now' AND status = 1")->sum('money');
        $today1['withdraw_count'] = Db::name('LcUserWithdrawRecord')->where("time BETWEEN '$today' AND '$now' AND status = 1")->count();
        $today1['new_user'] = Db::name('LcUser')->where("time BETWEEN '$today' AND '$now'")->count();
        $today1['invest'] = Db::name('LcInvest')->where("time BETWEEN '$today' AND '$now'")->count();
        $today1['invest_user_count'] = Db::name('LcInvest')->where("time BETWEEN '$today' AND '$now'")->group('uid')->count();
        $today1['invest_sum'] = Db::name('LcInvest')->where("time BETWEEN '$today' AND '$now'")->sum('money');
        $today1['invest_reward'] = Db::name('LcUserFunding')->where("time BETWEEN '$today' AND '$now' AND type = 1 AND fund_type = 6")->sum('money');
        $today_sys_sum_1 = Db::name('LcUserFunding')->where("time BETWEEN '$today' AND '$now' AND type = 1 AND fund_type = 1")->sum('money');
        $today_sys_sum_2 = Db::name('LcUserFunding')->where("time BETWEEN '$today' AND '$now' AND type = 2 AND fund_type = 1")->sum('money');
        $today1['sys_sum'] = $today_sys_sum_1 - $today_sys_sum_2;
        $today1['sys_reward'] = Db::name('LcUserFunding')->where("time BETWEEN '$today' AND '$now' AND type = 1 AND fund_type IN (7,8,9,10,11,12,13,14)")->sum('money');
        
        //昨日
        $report_yesterday1 = Db::name('LcUserReport')->where("time >= '$yesterday' AND time < '$today'")->find();
        $json_yesterday1= json_decode($report_yesterday1['json'], true);
        $yesterday1 = $json_yesterday1;
        
        
        //本月
        $firstDate = date('Y-m-01 00:00:00', strtotime(date("Y-m-d")));
        $lastDate = date('Y-m-d 23:59:59',strtotime("last day of this month",strtotime(date("Y-m-d"))));
        
        $report_month = Db::name('LcUserReport')->where("time BETWEEN '$firstDate' AND '$lastDate'")->select();
        
        $month['recharge'] = 0;
        $month['recharge_count'] = 0;
        $month['withdraw'] = 0;
        $month['withdraw_count'] = 0;
        $month['new_user'] = 0;
        $month['user_login_count'] = 0;
        $month['active_user_count'] = 0;
        $month['invest'] = 0;
        $month['invest_user_count'] = 0;
        $month['invest_sum'] = 0;
        $month['invest_reward'] = 0;
        $month['sys_sum'] = 0;
        $month['sys_reward'] = 0;
        $month['sys_income'] = 0;
        
        foreach ($report_month as &$report) {
            $json= json_decode($report['json'], true);
            $month['recharge'] = $month['recharge'] + $json['recharge'];
            $month['recharge_count'] = $month['recharge_count'] + $json['recharge_count'];
            $month['withdraw'] = $month['withdraw'] + $json['withdraw'];
            $month['withdraw_count'] = $month['withdraw_count'] + $json['withdraw_count'];
            $month['new_user'] = $month['new_user'] + $json['new_user'];
            $month['user_login_count'] = $month['user_login_count'] + $json['user_login_count'];
            $month['active_user_count'] = $month['active_user_count'] + $json['active_user_count'];
            $month['invest'] = $month['invest'] + $json['invest'];
            $month['invest_user_count'] = $month['invest_user_count'] + $json['invest_user_count'];
            $month['invest_sum'] = $month['invest_sum'] + $json['invest_sum'];
            $month['invest_reward'] = $month['invest_reward'] + $json['invest_reward'];
            $month['sys_sum'] = $month['sys_sum'] + $json['sys_sum'];
            $month['sys_reward'] = $month['sys_reward'] + $json['sys_reward'];
            $month['sys_income'] = $month['sys_income'] + $json['sys_income'];
        }
        
        //上月
        $lastMonthFirstDate = date('Y-m-01 00:00:00',strtotime('-1 month'));
        $lastMonthLastDate = date('Y-m-d 23:59:59',strtotime('-1 month'));
        
        $report_lastMonth = Db::name('LcUserReport')->where("time BETWEEN '$lastMonthFirstDate' AND '$lastMonthLastDate'")->select();
        
        $lastMonth['recharge'] = 0;
        $lastMonth['recharge_count'] = 0;
        $lastMonth['withdraw'] = 0;
        $lastMonth['withdraw_count'] = 0;
        $lastMonth['new_user'] = 0;
        $lastMonth['user_login_count'] = 0;
        $lastMonth['active_user_count'] = 0;
        $lastMonth['invest'] = 0;
        $lastMonth['invest_user_count'] = 0;
        $lastMonth['invest_sum'] = 0;
        $lastMonth['invest_reward'] = 0;
        $lastMonth['sys_sum'] = 0;
        $lastMonth['sys_reward'] = 0;
        $lastMonth['sys_income'] = 0;
        
        foreach ($report_lastMonth as &$report) {
            $json= json_decode($report['json'], true);
            $lastMonth['recharge'] = $lastMonth['recharge'] + $json['recharge'];
            $lastMonth['recharge_count'] = $lastMonth['recharge_count'] + $json['recharge_count'];
            $lastMonth['withdraw'] = $lastMonth['withdraw'] + $json['withdraw'];
            $lastMonth['withdraw_count'] = $lastMonth['withdraw_count'] + $json['withdraw_count'];
            $lastMonth['new_user'] = $lastMonth['new_user'] + $json['new_user'];
            $lastMonth['user_login_count'] = $lastMonth['user_login_count'] + $json['user_login_count'];
            $lastMonth['active_user_count'] = $lastMonth['active_user_count'] + $json['active_user_count'];
            $lastMonth['invest'] = $lastMonth['invest'] + $json['invest'];
            $lastMonth['invest_user_count'] = $lastMonth['invest_user_count'] + $json['invest_user_count'];
            $lastMonth['invest_sum'] = $lastMonth['invest_sum'] + $json['invest_sum'];
            $lastMonth['invest_reward'] = $lastMonth['invest_reward'] + $json['invest_reward'];
            $lastMonth['sys_sum'] = $lastMonth['sys_sum'] + $json['sys_sum'];
            $lastMonth['sys_reward'] = $lastMonth['sys_reward'] + $json['sys_reward'];
            $lastMonth['sys_income'] = $lastMonth['sys_income'] + $json['sys_income'];
        }
        
        
        //明细
        if(empty($i_time)){
            $monthDays = $this->getMonthDays();
        }else{
            $monthDays = $this->getDays($i_time);  
        }
        
        foreach($monthDays as $k=>$v){
            $first = date('Y-m-d 00:00:00', strtotime($v));
            $last = date('Y-m-d 23:59:59', strtotime($v));
            
            $report = Db::name('LcUserReport')->where("time BETWEEN '$first' AND '$last'")->find();
            $json= json_decode($report['json'], true);
            
            $day[$k] = $json;
            
            $day[$k]['date'] = $v;
            
        }
        return array('day' => $day,'today' => $today1,'yesterday' => $yesterday1,'month' => $month,'last_month'=>$lastMonth);
    }
    
    /**
     * 获取当前月已过日期
     * @return array
     */
    private function getDays($i_time)
    {
        
        $monthDays = [];
        $time = explode(" - ",$i_time);
        $firstDay = $time[0];
        $i = 0;
        $lastDay = $time[1];
        while (date('Y-m-d', strtotime("$firstDay +$i days")) <= $lastDay) {
            // if($i>=$now_day) break;
            $monthDays[] = date('Y-m-d', strtotime("$firstDay +$i days"));
            $i++;
        }
        return $monthDays;
    }

    /**
     * 获取当前月已过日期
     * @return array
     */
    private function getMonthDays()
    {
        $monthDays = [];
        $firstDay = date('Y-m-01', time());
        $i = 0;
        $now_day = date('d');
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        while (date('Y-m-d', strtotime("$firstDay +$i days")) <= $lastDay) {
            // if($i>=$now_day) break;
            $monthDays[] = date('Y-m-d', strtotime("$firstDay +$i days"));
            $i++;
        }
        return $monthDays;
    }

    /**
     * 修改密码
     * @login true
     * @param integer $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass($id)
    {
        $this->applyCsrfToken();
        if (intval($id) !== intval(session('user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if (!AdminService::instance()->isLogin()) {
            $this->error('需要登录才能操作哦！');
        }
        if ($this->request->isGet()) {
            $this->verify = true;
            $this->_form('SystemUser', 'admin@user/pass', 'id', [], ['id' => $id]);
        } else {
            $data = $this->_input([
                'password'    => $this->request->post('password'),
                'repassword'  => $this->request->post('repassword'),
                'oldpassword' => $this->request->post('oldpassword'),
            ], [
                'oldpassword' => 'require',
                'password'    => 'require|min:4',
                'repassword'  => 'require|confirm:password',
            ], [
                'oldpassword.require' => '旧密码不能为空！',
                'password.require'    => '登录密码不能为空！',
                'password.min'        => '登录密码长度不能少于4位有效字符！',
                'repassword.require'  => '重复密码不能为空！',
                'repassword.confirm'  => '重复密码与登录密码不匹配，请重新输入！',
            ]);
            $user = Db::name('SystemUser')->where(['id' => $id])->find();
            if (md5($data['oldpassword']) !== $user['password']) {
                $this->error('旧密码验证失败，请重新输入！');
            }
            if (Data::save('SystemUser', ['id' => $user['id'], 'password' => md5($data['password'])])) {
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 修改用户资料
     * @login true
     * @param integer $id 会员ID
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function info($id = 0)
    {
        if (!AdminService::instance()->isLogin()) {
            $this->error('需要登录才能操作哦！');
        }
        $this->applyCsrfToken();
        if (intval($id) === intval(session('user.id'))) {
            $this->_form('SystemUser', 'admin@user/form', 'id', [], ['id' => $id]);
        } else {
            $this->error('只能修改登录用户的资料！');
        }
    }

    /**
     * 清理运行缓存
     * @auth true
     */
    // public function clearRuntime()
    // {
    //     try {
    //         Console::call('clear');
    //         Console::call('xclean:session');
    //         $this->success('清理运行缓存成功！');
    //     } catch (HttpResponseException $exception) {
    //         throw $exception;
    //     } catch (\Exception $e) {
    //         $this->error("清理运行缓存失败，{$e->getMessage()}");
    //     }
    // }

    /**
     * 压缩发布系统
     * @auth true
     */
    // public function buildOptimize()
    // {
    //     try {
    //         Console::call('optimize:route');
    //         Console::call('optimize:schema');
    //         Console::call('optimize:autoload');
    //         Console::call('optimize:config');
    //         $this->success('压缩发布成功！');
    //     } catch (HttpResponseException $exception) {
    //         throw $exception;
    //     } catch (\Exception $e) {
    //         $this->error("压缩发布失败，{$e->getMessage()}");
    //     }
    // }
    /**
     * 导出报表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    // public function export_excel()
    // {
    //     $this->title = '';
    //     $this->fetch();
    // }
    /**
     * 确定导出报表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function export_save()
    {
    }
    /**
     * 导出Excel
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    // public function exportExcel()
    // {

    // }

}
